import router from '@/router'
import store from '@/store'
router.beforeEach(async(to, from, next) => {
  const token = store.getters.token
  const url = to.path
  const whiteList = ['/login', '/404']

  if (token && url === '/login') {
    next('/')
  }
  if (token && url !== '/login') {
    if (!store.getters.userId) {
      await store.dispatch('user/getUserInfo')
      const res = await store.dispatch(
        'permission/filterRoutes',
        store.state.user.userInfo.roles.menus
      )
      router.addRoutes([
        ...res,
        { path: '*', redirect: '/404', hidden: true }
      ])

      next(to.path)
    } else {
      next()
    }
  }

  if (!token && whiteList.includes(to.path)) {
    next()
  }
  if (!token && !whiteList.includes(to.path)) {
    next('/login')
  }
})
